<template>
  <div class="job-positions-container">
    <div class="header">
      <div class="left">
        <h2>我的岗位</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>发布岗位
        </el-button>
      </div>
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索岗位标题"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="positions"
        border
        stripe
        style="width: 100%"
        @row-click="row => console.log('Row clicked:', row)"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="岗位标题" min-width="150" />
        <el-table-column prop="category.name" label="岗位分类" width="120" />
        <el-table-column prop="quota" label="招聘人数" width="100" />
        <el-table-column prop="salary" label="时薪" width="100">
          <template #default="{ row }">
            ¥{{ row.salary }}
          </template>
        </el-table-column>
        <el-table-column prop="workLocation" label="工作地点" width="150" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRecruitmentStatusType(row)">
              {{ getRecruitmentStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                v-if="row.status === 'PENDING' || row.status === 'REJECTED'"
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!loading && (!positions || positions.length === 0)" class="empty-data">
        <el-empty description="暂无数据" />
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 岗位表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="650px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="岗位标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入岗位标题" />
        </el-form-item>
        <el-form-item label="岗位分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择岗位分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="招聘人数" prop="quota">
          <el-input-number v-model="form.quota" :min="1" />
        </el-form-item>
        <el-form-item label="时薪" prop="salary">
          <el-input-number v-model="form.salary" :min="0" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="工作时间" prop="workingHours">
          <el-input v-model="form.workingHours" placeholder="请输入工作时间" />
        </el-form-item>
        <el-form-item label="工作地点" prop="workLocation">
          <el-input v-model="form.workLocation" placeholder="请输入工作地点" />
        </el-form-item>
        <el-form-item label="岗位描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入岗位描述"
          />
        </el-form-item>
        <el-form-item label="岗位要求" prop="requirements">
          <el-input
            v-model="form.requirements"
            type="textarea"
            :rows="4"
            placeholder="请输入岗位要求"
          />
        </el-form-item>
        <el-form-item label="工作福利" prop="benefits">
          <el-input
            v-model="form.benefits"
            type="textarea"
            :rows="4"
            placeholder="请输入工作福利"
          />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="form.startDate"
            type="datetime"
            placeholder="选择开始日期"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="form.endDate"
            type="datetime"
            placeholder="选择结束日期"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMyPositions, createPosition, updatePosition, deletePosition, getCategories } from '@/api/teacher/jobPosition'
import { formatDate } from '@/utils/format'

// 表格数据
const loading = ref(false)
const positions = ref(null)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')

// 表单数据
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitting = ref(false)
const categories = ref([])

const form = ref({
  title: '',
  categoryId: null,
  description: '',
  quota: 1,
  salary: 0,
  workingHours: '',
  workLocation: '',
  requirements: '',
  benefits: '',
  startDate: null,
  endDate: null
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入岗位标题', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择岗位分类', trigger: 'change' }
  ],
  quota: [
    { required: true, message: '请输入招聘人数', trigger: 'blur' }
  ],
  salary: [
    { required: true, message: '请输入时薪', trigger: 'blur' }
  ]
}

// 重置数据的辅助函数
const resetTableData = () => {
  positions.value = []
  total.value = 0
}

// 获取岗位列表
const fetchPositions = async () => {
  try {
    loading.value = true
    resetTableData()
    const response = await getMyPositions({
      page: currentPage.value - 1,
      size: pageSize.value,
      search: searchQuery.value
    })
    
    if (response) {
      const { content, totalElements } = response
      if (Array.isArray(content)) {
        positions.value = content
        total.value = totalElements
        console.log('Data loaded:', { 
          positions: positions.value,
          total: total.value
        })
      } else {
        console.error('Invalid content format:', content)
      }
    }
  } catch (error) {
    console.error('Failed to fetch positions:', error)
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

// 获取岗位分类
const fetchCategories = async () => {
  try {
    const response = await getCategories()
    console.log('Categories response:', response)
    if (response) {
      categories.value = response
      console.log('Updated categories:', categories.value)
    }
  } catch (error) {
    console.error('Failed to fetch categories:', error)
    ElMessage.error('获取岗位分类失败')
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPositions()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPositions()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPositions()
}

// 处理添加
const handleAdd = () => {
  dialogTitle.value = '添加岗位'
  form.value = {
    title: '',
    categoryId: null,
    description: '',
    quota: 1,
    salary: 0,
    workingHours: '',
    workLocation: '',
    requirements: '',
    benefits: '',
    startDate: null,
    endDate: null
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑岗位'
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该岗位吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deletePosition(row.id)
      ElMessage.success('删除成功')
      fetchPositions()
    } catch (error) {
      console.error('Failed to delete position:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (form.value.id) {
      await updatePosition(form.value.id, form.value)
      ElMessage.success('更新成功')
    } else {
      await createPosition(form.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchPositions()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'PENDING':
      return 'warning'
    case 'APPROVED':
      return 'success'
    case 'REJECTED':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'PENDING':
      return '待审核'
    case 'APPROVED':
      return '已通过'
    case 'REJECTED':
      return '已拒绝'
    default:
      return '未知'
  }
}

// 获取招聘状态类型
const getRecruitmentStatusType = (row) => {
  if (row.status !== 'APPROVED') {
    return 'info'
  }
  return row.active ? 'success' : 'warning'
}

// 获取招聘状态文本
const getRecruitmentStatusText = (row) => {
  if (row.status !== 'APPROVED') {
    return '未开始'
  }
  return row.active ? '招聘中' : '已结束'
}

// 确保在组件挂载时获取数据
onMounted(async () => {
  console.log('Component mounted')
  try {
    await Promise.all([
      fetchCategories(),
      fetchPositions()
    ])
    console.log('Initial data loaded')
  } catch (error) {
    console.error('Failed to load initial data:', error)
  }
})
</script>

<style scoped>
.job-positions-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-input {
  width: 300px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-button-group) {
  .el-button {
    padding: 5px 12px;
  }
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}
</style> 